package com.briup.web.interceptor;

import com.briup.exception.ServiceException;
import com.briup.util.JwtUtils;
import com.briup.util.ResultCode;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @BelongsProject: cms
 * @BelongsPackage: com.briup.web.interceptor
 * @Author: li
 * @CreateTime: 2024-11-20  19:19
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(@NonNull HttpServletRequest httpServletRequest,
                             @NonNull HttpServletResponse httpServletResponse,
                             @NonNull Object object) {
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        // 从 HTTP请求头中取出 token
        String token =
                httpServletRequest.getHeader("Authorization");
        if (token == null) {
            log.info("无token,请重新登录");
            throw new ServiceException(ResultCode.USER_NOT_LOGIN);
        }
        // 验证 token
        try {
            //解析JWT
            Claims claims = JwtUtils.parseJWT(token);
            String id = String.valueOf(claims.get("userId"));
            //专门为 /auth/user/info 提供服务
            httpServletRequest.setAttribute("userId",id);
        }catch (ExpiredJwtException e){
            log.info("登录到期");
            throw new ServiceException(ResultCode.USER_NOT_LOGIN);
        }catch (MalformedJwtException e){
            log.info("令牌失效");
            throw new ServiceException(ResultCode.PARAM_IS_INVALID);
        }catch (Exception e){
            log.error(e.getMessage());
            //服务器内部错误
            throw new
                    ServiceException(ResultCode.SYSTEM_INNER_ERROR);
        }
        return true;
    }
}
